package hlhj.fhp.supreme.activitys

import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import com.alipay.sdk.app.PayTask
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.Contents
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.javabean.AliPayBean
import hlhj.fhp.supreme.javabean.CartPayBean
import hlhj.fhp.supreme.javabean.PayfailEvent
import hlhj.fhp.supreme.javabean.WxPayBean
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import kotlinx.android.synthetic.main.activity_order_pay_aty.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class OrderPayAty : BaseAty() {

    private  var payType=2
    private var orderSign=""
    private var money=""
    private lateinit var api:IWXAPI
    private val halder= @SuppressLint("HandlerLeak")
    object : Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val result = msg!!.obj as Map<String, String>
            val status = result["resultStatus"]
            val ss = result["sub_msg"]
            LogUtil.logi("结果----$ss")
            if (status == "9000") {
                MyUtils.toast("支付成功")
                setResult(-1)
                val intent = Intent(this@OrderPayAty, PaySuccessAty::class.java)
                intent.putExtra("type","1")
                startActivity(intent)
                setResult(-1)
                finish()
            }else{
                val intent = Intent(this@OrderPayAty, PaySuccessAty::class.java)
                intent.putExtra("type","2")
                startActivity(intent)
                setResult(-1)
                finish()
            }
        }
    }
    override fun getContentId(): Int {
        return R.layout.activity_order_pay_aty
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        orderSign=intent.getStringExtra("order")
        money=intent.getStringExtra("money")
        tvPrice.text="￥ ${money}"
        api=WXAPIFactory.createWXAPI(this,Contents.WXAPPKEY)
        api.registerApp(Contents.WXAPPKEY)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private val SDK_PAY_FLAG: Int=1

    override fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
        loZfb.setOnClickListener {
            payType=2
            cbZfb.isChecked=true
            cbWX.isChecked=false
        }

        loWx.setOnClickListener {
            payType=1
            cbZfb.isChecked=false
            cbWX.isChecked=true
        }



        btCommit.setOnClickListener {
            when(payType){
                1->{
                    OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.ORDER_PAY)
                            .params("order_sn",orderSign)
                            .params("pay_type",1)
                            .execute(object : JsonCallBack<WxPayBean>(this){
                                override fun onSuccess(response: Response<WxPayBean>?) {
                                    val bean = response?.body()
                                    if (bean?.code==1){
                                        runOnUiThread {
                                            val data = bean?.data
                                            val req = PayReq()
                                            req.appId=data.appid
                                            req.partnerId = data.partnerid
                                            req.prepayId = data.prepayid
                                            req.nonceStr = data.noncestr
                                            req.timeStamp = data.timestamp.toString()
                                            req.packageValue = data.packageX
                                            req.sign = data.sign
                                            req.extData=""
                                            api!!.sendReq(req)
                                            finish()
                                        }
//                                setResult(-1)
//                                finish()

                                    }else{
                                        MyUtils.toast(bean?.msg)
                                    }
                                }
                            })
                }
                2->{
                    OkGo.post<AliPayBean>(Urls.BaseUrl+Urls.ORDER_PAY)
                            .params("order_sn",orderSign)
                            .params("pay_type",2)
                            .execute(object :JsonCallBack<AliPayBean>(this){
                                override fun onSuccess(response: Response<AliPayBean>?) {
                                    val body = response?.body()
                                    if (body?.code==1){
                                        val s = body?.data.pay_data
                                        LogUtil.logi(s)
                                        val runnable = Runnable {
                                            val alipay = PayTask(this@OrderPayAty)
                                            val result = alipay.payV2(s, true)
                                            val msg = Message()
                                            msg.what = SDK_PAY_FLAG
                                            msg.obj = result
                                            halder.sendMessage(msg)
                                        }
                                        val t = Thread(runnable)
                                        t.start()
                                    }
                                }
                            })
                }
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handCart(event:CartPayBean){
        this@OrderPayAty.setResult(-1)
        val intent = Intent(this, PaySuccessAty::class.java)
        intent.putExtra("type","1")
        startActivity(intent)
        setResult(-1)
        finish()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handPayFail(event: PayfailEvent){
        this.setResult(-1)
        val intent = Intent(this, PaySuccessAty::class.java)
        intent.putExtra("type","2")
        startActivity(intent)
        finish()
    }

}
